package net.spacebeeshooter.items;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;

import net.spacebeeshooter.main.ErrorGenerator;

public final class ItemConfigLoader {

	private final String itemPath;
	private final String defaultPath;
	private final HashMap<String,ParseableType<?>> allowedTypes;
	private final ConfigSeparator separator;
	
	public ItemConfigLoader(String itemPath, String defaultPath, ParseableType<?>[] allowedTypes, ConfigSeparator separator) {
		this.itemPath = itemPath;
		this.defaultPath = defaultPath;
		this.allowedTypes = new HashMap<String,ParseableType<?>>();
		for (ParseableType<?> type : allowedTypes) {
			this.allowedTypes.put(type.getType().getSimpleName(), type);
		}
		this.separator = separator;
	}
	
	public Item loadItemConfiguration() throws IOException {
		BufferedReader itemReader = new BufferedReader(new FileReader(new File(itemPath)));
		String[] values = itemReader.readLine().split(separator.getNameSeparator());
		String[] types = itemReader.readLine().split(separator.getTypeSeparator());
		itemReader.close();
		BufferedReader defaultReader = new BufferedReader(new FileReader(new File(defaultPath)));
		String[] defaultValues = defaultReader.readLine().split(separator.getDefaultValueSeparator());
		defaultReader.close();
		int valueLength = values.length;
		String incorrectFileFormatErrorMessage = "File format is incorrect";
		if (types.length == valueLength) {
			ItemValue[] itemValues = new ItemValue[valueLength];
			for (int i = 0; i != valueLength; i ++) {
				String currentValue = values[i];
				String currentType = types[i];
				String currentDefaultValue = defaultValues[i].substring(1, defaultValues[i].length() - 1);
				if (allowedTypes.containsKey(currentType)) {
					ParseableType<?> currentParseableType = allowedTypes.get(currentType);
					try {
						itemValues[i] = new ItemValue(currentValue, currentParseableType.getType(), currentParseableType.getConverter().convert(currentDefaultValue));
					} catch (NumberFormatException e) {
						new ErrorGenerator().generateErrorMessage(incorrectFileFormatErrorMessage);
						throw new IllegalArgumentException();
					}
					
				}
			}
			return new Item(itemValues);
		} else {
			new ErrorGenerator().generateErrorMessage(incorrectFileFormatErrorMessage);
			throw new IllegalArgumentException();
		}
	}
}
